package org.xhy.security.filter;

import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.xhy.security.handler.MyAuthenticationFailureHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 验证码验证
 */
public class CodeCheckFilter extends OncePerRequestFilter {

    /*属性注入 set注入！*/
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    public void setMyAuthenticationFailureHandler(MyAuthenticationFailureHandler myAuthenticationFailureHandler){
        this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
    }

    //路径匹配器
    private AntPathMatcher antPathMatcher =  new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //判断URL是smslog才做检查
        if (!antPathMatcher.match("/smslogin",request.getRequestURI())){
            filterChain.doFilter(request,response);
            return;
        }

        //从request获取参数
        String code = request.getParameter("code");
        String phone = request.getParameter("phone");
        if (!StringUtils.hasText(code)){
            //失败后 条件不足异常InsufficientAuthenticationException
            myAuthenticationFailureHandler.onAuthenticationFailure(request,response,new InsufficientAuthenticationException("验证码为空！"));
            return;
        }

        //从session中获取验证码
        Map<String,String> sessonCode = (Map<String, String>) request.getSession().getAttribute("sessonCode");
        if (sessonCode == null){
            //失败后 条件不足异常InsufficientAuthenticationException
            myAuthenticationFailureHandler.onAuthenticationFailure(request,response,new InsufficientAuthenticationException("验证码错误！请重新发送！"));
            return;
        }

        //判断手机号、验证码正确性
        if (!sessonCode.get("code").equalsIgnoreCase(code)){
            //失败后 条件不足异常InsufficientAuthenticationException
            myAuthenticationFailureHandler.onAuthenticationFailure(request,response,new InsufficientAuthenticationException("验证码错了！重来！"));
            return;
        }
        if (!sessonCode.get("phone").equalsIgnoreCase(phone)){
            //失败后 条件不足异常InsufficientAuthenticationException
            myAuthenticationFailureHandler.onAuthenticationFailure(request,response,new InsufficientAuthenticationException("手机号错了！重来！"));
            return;
        }

        //都正确放行 filterChain调用链
        filterChain.doFilter(request,response);

    }
}
